import 'package:asperm/tools/auth.dart';
import 'package:asperm/tools/current_locale.dart';
import 'package:asperm/tools/router.dart';
import 'package:asperm/tools/storage.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import 'package:provider/provider.dart';

import 'generated/l10n.dart';
import 'package:flutter_localizations/flutter_localizations.dart';


final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
RouteObserver<PageRoute> routeObserver = RouteObserver<PageRoute>();

Future<void> main() async {
  // runApp(const MyApp());

  await ScreenUtil.ensureScreenSize();
  print('========main');

  initializedApp();
}

Future<void> initializedApp() async {
  print('========initializedApp');

  await SpUtil.getInstance();
  WidgetsFlutterBinding.ensureInitialized();
  LanguageProvider languageProvider = LanguageProvider();
  languageProvider.initialize();
  //初始化日志工具
  // LogUtils.init();
  //设置图片缓存
  //缓存个数 100
  PaintingBinding.instance.imageCache.maximumSize=100;
  //缓存大小 50m
  PaintingBinding.instance.imageCache.maximumSizeBytes= 50 << 20;
// 初始化通知帮助类
//   NotificationHelper notificationHelper = NotificationHelper();
//   await notificationHelper.initialize();

  // NotificationHelper().configureLocalTimeZone();
  // NotificationHelper.getInstance().initialize();
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
  ]);

  realRunApp(languageProvider);
}


void realRunApp(LanguageProvider languageProvider) async {
  debugPaintSizeEnabled = false;
  // HttpOverrides.global = MyHttpoverrides();
  // ByteData data = await PlatformAssetBundle().load('assets/ca/b8075632aa21ff1f.pem');
  // SecurityContext.defaultContext.setTrustedCertificatesBytes(data.buffer.asUint8List());

  runApp(MultiProvider(
      providers: [ChangeNotifierProvider.value(value: languageProvider)],
      child: MyApp()));
}


class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, designSize: const Size(375, 812));
    if (Theme.of(context).platform == TargetPlatform.android) {
      SystemUiOverlayStyle _style = const SystemUiOverlayStyle(
          statusBarColor: Colors.transparent,
          statusBarIconBrightness: Brightness.dark);
      SystemChrome.setSystemUIOverlayStyle(_style);
    }

    String initialRoute =  '/';
    if (!isLogin()) {
      initialRoute =  '/login';
    }

    return Consumer<LanguageProvider>(
        builder: (context, languageProvider, child) {
          print('========切换了语言');

          return MaterialApp(
            theme: ThemeData(
              appBarTheme: AppBarTheme(
                /// 设置AppBar 的表面颜色为透明色
                surfaceTintColor: Colors.transparent,
              ),
              highlightColor: Color.fromRGBO(0, 0, 0, 0),
              splashColor: Color.fromRGBO(0, 0, 0, 0),
            ),
            navigatorObservers: [routeObserver],
            navigatorKey: navigatorKey,
            initialRoute: initialRoute,
            // routes: routes,
            onGenerateRoute: onGenerateRoute,
            debugShowCheckedModeBanner: false,
            builder: EasyLoading.init(
              builder: (context, child) {
                return MediaQuery(
                  // 设置字体大小和粗细不跟随系统变化
                  data: MediaQuery.of(context).copyWith(
                      boldText: false, textScaler: TextScaler.linear(1.0)),
                  child: child ?? Container(),
                );
              },
            ),
            localizationsDelegates: const [
              GlobalMaterialLocalizations.delegate,
              GlobalWidgetsLocalizations.delegate,
              GlobalCupertinoLocalizations.delegate,
              S.delegate
            ],
            locale: languageProvider.currentLocale,
            supportedLocales: const [
              Locale('en', 'US'),
              // Locale('zh', 'CN'),
              // Locale('es', 'ES')
            ],
          );
        });
  }
}

